package com.batchbrake.queue;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.Timer;
import javax.swing.table.TableCellRenderer;

import org.jdesktop.swingx.JXTable;

public class QueueTable extends JXTable implements ActionListener {
	private Font tableFont = null;
	private Map<QueueEntity, QueueCellRenderer> renderers = new HashMap<QueueEntity, QueueCellRenderer>();
	private Timer repaintTimer = new Timer(500, this);
	
	public QueueTable() {
		super();
		tableFont = getFont();
	}
	
	@Override
	public TableCellRenderer getCellRenderer(int row, int column) {
		QueueEntity e = (QueueEntity) getValueAt(row, column);
		
		if( renderers.containsKey(e) ) {
			return renderers.get(e);
		} else {
			QueueCellRenderer renderer = new QueueCellRenderer();
			renderers.put(e, renderer);
			return renderer;
		}
	}

	
	public void setTimerEnabled(boolean enabled) {
		if( enabled ) {
			repaintTimer.start();
		} else {
			repaintTimer.stop();
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		repaint();
	}

	
	
	
	
	private Polygon createPolygon(Point... points) {
		Polygon p = new Polygon();
		for( int i = 0; i < points.length; i++ ) {
			p.addPoint(points[i].x, points[i].y);
		}
		return p;
	}
	
	private Polygon getArrow() {
		int h1 = 30;
		int w1 = 8;
		int w2 = 10;
		
		Point A = new Point(20,20);
		Point B = new Point(A.x - w1, A.y + h1);
		Point C = new Point(A.x, A.y + 2*h1);
		Point D = new Point(A.x + w2, C.y);
		Point E = new Point(B.x + w2, B.y);
		Point F = new Point(A.x + w2, A.y);
		
		return createPolygon(A, B, C, D, E, F);
	}
	
	@Override
	public void paint(Graphics graphics) {
		Graphics2D g = (Graphics2D)graphics;
		g.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
		g.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
		
		if( getRowCount() == 0 ) {
			g.setFont(tableFont);
			g.setColor(Color.white);
			g.fillRect(0, 0, this.getWidth(), this.getHeight());
			
			g.setColor(new Color(0f,0f,0f,0.3f));
			
			Polygon arrow = getArrow();
			g.fillPolygon(arrow);
			
			g.setColor(new Color(0f,0f,0f,0.5f));
			int d = -3;
			arrow.translate(d, d);
			g.fillPolygon(arrow);
			
			String[] queueToolsInfo = new String[] {
					"Manage your queue using the ",
					"available actions on the left"
			};
			
			g.setColor(Color.black);
			for( int i = 0; i < queueToolsInfo.length; i++ ) {
				g.drawString(queueToolsInfo[i], 40, 43 + i*g.getFontMetrics().getHeight());
			}
		} else {
			super.paint(graphics);
		}
	}

}
